import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/* 验证码校验组件 */

class CodeInput extends StatefulWidget {
  const CodeInput(
      {super.key, required this.codeController, required this.getCode});
  final TextEditingController codeController;
  final Function getCode;

  @override
  State<StatefulWidget> createState() => CodeInputState();
}

class CodeInputState extends State<CodeInput> {
  int emailCodeCountdown = 0;
  Timer? timer;

  void count() {
    setState(() {
      emailCodeCountdown = 60;
    });
    timer = Timer.periodic(
      const Duration(seconds: 1),
      (timer) {
        try {
          setState(() {
            emailCodeCountdown = emailCodeCountdown - 1;
          });
        } catch (e) {}
        if (emailCodeCountdown <= 0) {
          emailCodeCountdown = 0;
          timer.cancel();
        }
      },
    );
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      textInputAction: TextInputAction.next,
      controller: widget.codeController,
      keyboardType: TextInputType.number,
      inputFormatters: [
        FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
      ],
      decoration: InputDecoration(
        prefixIcon: const Icon(Icons.camera_outlined),
        hintText: "",
        labelText: "验证码",
        suffixIcon: ElevatedButton(
          onPressed: emailCodeCountdown > 0
              ? null
              : () async {
                  if (await widget.getCode() == true) {
                    count();
                  }
                },
          child: SizedBox(
            width: 70,
            child: Center(
              child: Text(
                  emailCodeCountdown == 0 ? '获取验证码' : '$emailCodeCountdown  秒'),
            ),
          ),
        ),
      ),
    );
  }
}
